<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="contractInitialId" label="合同">
          <Contract v-model="listQuery.contractInitialId" keyName="id" keyShow="name" placeholder="合同" title="合同查询" />
        </el-form-item>
        <!--
        <el-form-item prop="batch" label="批次号">
          <el-input v-model="listQuery.batch" placeholder="批次号" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="cashType" label="请款类型">
          <el-select v-model="listQuery.cashType" class="m-2" placeholder="请选择" disabled>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('ContractInitialCashType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item prop="cashUserId" label="请款经办人">
          <el-input v-model="listQuery.cashUserId" placeholder="请款经办人" @keyup.enter="handleFilter" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="cashDepartmentId" label="请款经办人部门">
          <el-input v-model="listQuery.cashDepartmentId" placeholder="请款经办人部门" @keyup.enter="handleFilter" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="cashAmount" label="请款金额">
          <el-input v-model="listQuery.cashAmount" placeholder="请款金额" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="state" label="请款状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('ContractInitialCashState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <!--
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
          -->
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <!-- <el-table-column align="center" label="合同ID" prop="contractInitialId" min-width="120px" sortable show-overflow-tooltip /> -->
      <el-table-column align="center" label="合同名称" prop="name" min-width="120px" sortable show-overflow-tooltip></el-table-column>
      <!--
      <el-table-column align="center" label="批次号" prop="batch" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.batch }}</template>
      </el-table-column>
      -->
      <el-table-column align="center" label="请款类型" prop="cashType" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <DictTag :dict-list="getDictList('ContractInitialCashType')" :dict-key="row.cashType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="请款经办人" prop="cashUserId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.cashUserId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="请款经办人部门" prop="cashDepartmentId" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.cashDepartmentId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="请款金额" prop="cashAmount" min-width="140px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.cashAmount" /></template>
      </el-table-column>
      <el-table-column align="center" label="请款状态" prop="state" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ContractInitialCashState')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleExpenditureReimbursement(row)" v-if="row.state === '2'">生成报账单</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          -->
          <el-button type="success" link @click="handleApprove(row)">审批流程</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="InfoFilled"
                         icon-color="#626AEF"
                         title="您确定撤回么？"
                         @confirm="handleRevocation(row)"
                         v-if="checkAuthByCode('') && ['1'].includes(row.state)">
            <template #reference>
              <el-button type="danger" link>撤回</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto" label-suffix="：">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="合同ID" prop="contractInitialId">
          <el-input v-model="obj.contractInitialId" type="number" placeholder="请输入合同ID" />
        </el-form-item>
        <el-form-item label="批次号" prop="batch">
          <el-input v-model="obj.batch" placeholder="请输入批次号，最多输入20个字符" />
        </el-form-item>
        <el-form-item label="请款类型" prop="cashType">
          <el-select v-model="obj.cashType" class="m-2" placeholder="请选择">
            <el-option key="" label="请选择" value="" />
            <el-option v-for="item in getDictList('ContractInitialCashType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="请款经办人" prop="cashUserId">
          <el-input v-model="obj.cashUserId" type="number" placeholder="请输入请款经办人" />
        </el-form-item>
        <el-form-item label="请款经办人部门" prop="cashDepartmentId">
          <el-input v-model="obj.cashDepartmentId" type="number" placeholder="请输入请款经办人部门" />
        </el-form-item>
        <el-form-item label="请款金额" prop="cashAmount">
          <el-input-number v-model="obj.cashAmount" placeholder="请输入请款金额" />
        </el-form-item>
        <el-form-item label="请款状态" prop="state">
          <el-radio-group v-model="obj.state">
            <el-radio-button v-for="(item,index) in getEnumList('ContractInitialCashState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogApproveVisible" title="审批流程" width="55%" top="2vh">
      <approveTimeline :businessType="approveOrderBusinessTypes().contractCash" :businessId="obj.id" />
      <div style="text-align:right;margin: 1.875rem 0;">
        <el-button type="danger" @click="dialogApproveVisible=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doDelete, doGet, doGetDownload, doPost, doPut} from '@/config/http'
import {
  alertErrorMsg,
  approveOrderBusinessTypes,
  customValidator,
  getListPageSize,
  notifySuccess,
  svc
} from '@/config/common'
import InputTagDialog from '@/components/InputTag/inputTagDialog.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';
import Contract from "@/views/components/contract/selectContract.vue";
import approveTimeline from "@/views/components/base/approveTimeline.vue";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  contractInitialId: null, // 合同ID
  batch: null, // 批次号
  cashType: null, // 请款类型
  cashUserId: null, // 请款经办人
  cashDepartmentId: null, // 请款经办人部门
  cashAmount: null, // 请款金额
  state: null, // 请款状态
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'contractInitialCash_nocache',
  components: {approveTimeline, Contract, SvgIcon, InputTagDialog},
  mixins: [baseConfig],
  data() {
    const svc = 'icims-api'
    return {
      svc,
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        contractInitialId: null,
        batch: 'latest',
        cashType: '2',
        cashUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        cashDepartmentId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
        cashAmount: null,
        state: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      dialogApproveVisible: false,
      rules: {
        contractInitialId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '合同ID', trigger: ['blur', 'change'] }],
        batch: [{ required: false, validator: customValidator, min: 0, max: 20, label: '批次号', trigger: ['blur', 'change'] }],
        cashType: [{ required: false, validator: customValidator, min: 0, max: 20, label: '请款类型', trigger: ['blur', 'change'] }],
        cashUserId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '请款经办人', trigger: ['blur', 'change'] }],
        cashDepartmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '请款经办人部门', trigger: ['blur', 'change'] }],
        cashAmount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '请款金额', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '请款状态', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
      organizationList: initListStore().organizationList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'contractOutgoings'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    // this.initList()
    this.getList()
  },
  methods: {
    useUserStore,
    approveOrderBusinessTypes,
    // async initList() {
    //   let p1 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2])
    //   this.userList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    // },
    async getList() {
      this.listLoading = true
      let res = await doGet(this.svc, '/contract-initial-cash/page', this.listQuery)
      this.listLoading = false
      let list = res['records']
      this.total = parseInt(res['total'])
      if (list.length > 0) {
        let ids = []
        list.map(item => ids.push(item.contractInitialId))
        let p1 = await doGet(this.svc, '/contract-initial/ids', {ids: ids.join(',')}, false) // 初始合同
        let idsObjs = p1.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
        this.list = list.map(item => {
          let index = idsObjs.findIndex(item1 => item1.id === item.contractInitialId)
          item.name = idsObjs[index].name
          return item
        })
      } else {
        this.list = list
      }
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/contract-initial-cash/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, `/contract-initial-cash/${row.id}`, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        this.dialogVisible = false
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      switch (this.dialogType) {
        case 'add': {
          doPost(this.svc, '/contract-initial-cash/add', this.obj).then(() => {
            notifySuccess('新增成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        }
        case 'edit': {
          doPut(this.svc, '/contract-initial-cash/modify', this.obj).then(() => {
            notifySuccess('修改成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        }
      }
    },
    handleExpenditureReimbursement(row) {
      let query = {
        oper: 'add',
        contractInitialCashId: row.id,
      }
      this.goTargetByName('expenditureReimbursementEdit', query)
    },
    handleRevocation(row) {
      doPost(this.svc, `/customContractInitial/revocationContractInitialCash/${row.id}`, {}, true).then(() => {
        notifySuccess('撤回成功')
        this.getList()
      })
    },
    handleApprove(row) {
      this.obj = Object.assign({}, row)
      this.dialogApproveVisible = true
    },
  }
}
</script>
